#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "inc/hw_types.h"
#include "driverlib/sysctl.h"
#include "driverlib/uart.h"
#include "driverlib/gpio.h"
#include "driverlib/uart.h"
#include "fifo.h"
#include "adc_c.h"
#include "edisk.h"
#include "efile.h"
#include "uart.h"
#include "LM3SXXXX.H"

void(*UART_HANDLER)(char* buffer);
_tFIFO UART_RX_FIFO;

//********************************UARTSend*************************************
//	Send a string to the UART.
//! \param None
//! \return None
//*****************************************************************************
void
UARTSend(const unsigned char *pucBuffer)
{
	unsigned long ulCount;
	tBoolean putSuccessful;
	ulCount = strlen((const char*)pucBuffer);
    //
    // Loop while there are more characters to send.
    //
    while(ulCount > 0)
    {
        //
        // Write the next character to the UART.
        //
        putSuccessful = UARTCharPutNonBlocking(UART0_BASE, *pucBuffer);
		if(putSuccessful){
			*pucBuffer++;
			 ulCount--;
		}
    }
}



void
UARTDefaultHandler(char* buffer){
	
	UARTSend("Recieved Command!\r\n");
		
}

void UARTConsoleHandler(void){
	char buffer[FIFO_SIZE]={0};
	int i,fifosize;
	
	fifosize = FIFO_GetSize(UART_RX_FIFO);
	
	for(i=0; i < fifosize; i++){
		FIFO_GetSingle(UART_RX_FIFO, &(buffer[i]));
	}
	UART_HANDLER(buffer);		
}


//*****************************************************************************
//
// This function sets up UART0 to be used for a console to display information
// as the example is running.
//
//*****************************************************************************
void
UARTIntHandler(void)
{
    char c;
	unsigned long ulStatus;

    //
    // Get the interrrupt status.
    //
    ulStatus = UARTIntStatus(UART0_BASE, true);

    //
    // Clear the asserted interrupts.
    //
    UARTIntClear(UART0_BASE, ulStatus);

    //
    // Loop while there are characters in the receive FIFO.
    //
    while(UARTCharsAvail(UART0_BASE))
    {
        //
        // Read the next character from the UART and write it to a FIFO
        //
		c = UARTCharGetNonBlocking(UART0_BASE);
		
		if(c == '\n' || c == '\r'){
			c = '\0';
		}
		if(c != 0x7f){
        	FIFO_PutSingle(UART_RX_FIFO,&c);
		}else{
			FIFO_DeleteLastEntry(UART_RX_FIFO);//If backspace, then delete last char from fifo
		}
		if(c == '\0'){
			UARTConsoleHandler();	
		}else {
			UARTCharPutNonBlocking(UART0_BASE, c);
		}
    }
}

//********************************UARTInit*************************************
//	Initializes the UART
//! \param None
//! \return None
//*****************************************************************************
void
UARTInit(void){
	UART_RX_FIFO = FIFO_CreateFifo(FIFO_SIZE, sizeof(char));
	UART_HANDLER = UARTDefaultHandler;
}
